import { Component, OnInit } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd/message';
import { ActivatedRoute } from '@angular/router';
import { NzModalService } from 'ng-zorro-antd/modal';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';

import { storageDeliveryMethodArrs } from '../../xstorage-manage-pipes/storage-manage-z.pipe';
import { CommonService } from '../../../../services-common/common.service';
import { PermissionService } from '../../../../service/permission.service';
import { StorageCommonService } from '../../xstorage-manage-services/storage-common.service';
import { StorageTransferOrderService } from '../../xstorage-manage-services/storage-transfer-order.service';

@Component({
  selector: 'app-storage-transfer-details',
  templateUrl: './storage-transfer-details.component.html',
  styleUrls: ['./storage-transfer-details.component.scss']
})
export class StorageTransferDetailsComponent implements OnInit {

  routeParams: any = {};
  detailsData: any = {};

  detailedTableData: any[] = [];

  supplierOptions: any[] = []; // 供应商Options
  storeOptions: any[] = []; // 仓库Options
  locationOptions: any[] = []; // 库位Options
  allocationTypeOptions: any = []; // 调拨类型Options
  logisticsOptions: any[] = []; // 物流Options

  /**
   * 作废 Modal
   * ----------------------------------------------------------------
   */
  isZfVisible = false;
  submitZfLoading = false;
  toVoidRemark = ''; // 作废备注

  /**
   * SN 信息 Modal
   * ----------------------------------------------------------------
   */
  isSninfoVisible = false;
  snModalTable: any[] = [];

  /**
   * 多库位 信息 Modal
   * ----------------------------------------------------------------
   */
  isDkwVisible = false;
  locationOneTable: any = [];
  locationTwoTable: any = [];

  /**
   * 商品明细 table check
   * ----------------------------------------------------------------
   */
  checked = false;
  indeterminate = false;
  listOfCurrentPageData: readonly any[] = [];
  setOfCheckedId = new Set<number>();

  updateCheckedSet(id: number, checked: boolean): void {
    if (checked) {
      this.setOfCheckedId.add(id);
    } else {
      this.setOfCheckedId.delete(id);
    }
  }

  onItemChecked(id: number, checked: boolean): void {
    this.updateCheckedSet(id, checked);
    this.refreshCheckedStatus();
  }

  onAllChecked(value: boolean): void {
    const listOfCurrentPageData = this.listOfCurrentPageData.filter(item => item.lineState === 0);
    listOfCurrentPageData.forEach(item => this.updateCheckedSet(item.id, value));
    this.refreshCheckedStatus();
  }

  onCurrentPageDataChange($event: readonly any[]): void {
    this.listOfCurrentPageData = $event;
    this.refreshCheckedStatus();
  }

  refreshCheckedStatus(): void {
    const listOfCurrentPageData = this.listOfCurrentPageData.filter(item => item.lineState === 0);
    this.checked = listOfCurrentPageData.every(item => this.setOfCheckedId.has(item.id)) && listOfCurrentPageData.length > 0;
    this.indeterminate = listOfCurrentPageData.some(item => this.setOfCheckedId.has(item.id)) && !this.checked;
  }

  constructor(
    private msg: NzMessageService,
    private activatedRoute: ActivatedRoute,
    private modal: NzModalService,
    private fb: FormBuilder,
    private commonService: CommonService,
    public permission: PermissionService,
    private storageCommonService: StorageCommonService,
    private services: StorageTransferOrderService
  ) {
    activatedRoute.queryParams.subscribe((res: any) => {
      this.routeParams = res || {};
    })
  }

  ngOnInit(): void {
    this.loadSupplierList();
    this.loadStoreList();
    this.loadLocationOptions();
    this.loadAllocationTypeOptions();
    this.loadLogisticsData();

    this.loadDetailsData();
  }

  // 查询物流
  async loadLogisticsData() {
    const res: any = await this.commonService.getDictList('logistics_company');
    this.logisticsOptions = (res && res.length) ? res.filter((ele: any) => ['JD', 'SF'].includes(ele.content)) : [];
  }

  // 查询供应商
  async loadSupplierList() {
    const res: any = await this.commonService.getSupplierList();
    // 状态为正常de
    this.supplierOptions = res.filter((item: any) => item.state === 1);
  }

  // 调拨类型Options
  async loadAllocationTypeOptions() {
    const res = await this.commonService.getDictList('allocation_type');
    this.allocationTypeOptions = res || [];
  }

  // 查询仓库
  async loadStoreList() {
    let params = {
      page: 1,
      pageSize: 9999
    }
    const {code, data, message}: any = await this.storageCommonService.getWarehouseList(params);
    if (code === 0) {
      this.storeOptions = data?.records.filter((item: any) => [1].includes(item.state));
    } else {
      this.msg.error(message);
    }
  }

  // 查询库位Options
  async loadLocationOptions() {
    let params = {
      // whId: !this.commonService.isEmpty(this.routeParams.whId) ? this.routeParams.whId : '',
      page: 1,
      pageSize: 1000
    }
    const {code, data, message}: any = await this.storageCommonService.getLocationList(params);
    if (code === 0) {
      this.locationOptions = data.records || [];
    } else {
      this.msg.error(message);
    }
  }

  async loadDetailsData() {
    let params = {
      id: this.routeParams.id
    }
    const msgId = this.msg.loading('数据加载中..', { nzDuration: 0 }).messageId;
    const {code, data, message}: any = await this.services.getAllocationDetailData(params);
    this.msg.remove(msgId);

    if (code === 0) {
      const {delivery, list} = data || {};

      this.detailsData = delivery || {};
      this.detailedTableData = list || [];
    } else {
      this.msg.error(message);
    }
  }

  /**
   * 作废
   * ----------------------------------------------------------------
   */
  showTovoidModal(item?: any) {
    if (!this.setOfCheckedId.size) {
      this.msg.warning('请先选择所需作废项');
      return
    }

    this.toVoidRemark = '';
    this.isZfVisible = true;
  }

  async submitToVoidData() {
    if (this.commonService.isEmpty(this.toVoidRemark)) {
      this.msg.warning('请输入备注');
      return
    }

    let params = {
      ids: [...this.setOfCheckedId],
      state: 1, // 状态 0正常 1已作废
      note: this.toVoidRemark
    }
    this.submitZfLoading = true;
    const {code, message}: any = await this.services.detailsNullifyData(params);
    this.submitZfLoading = false;

    if (code === 0) {
      this.isZfVisible = false;
      this.setOfCheckedId.clear();
      this.msg.success('操作成功');
      this.loadDetailsData();
    } else {
      this.msg.error(message);
    }
  }

  // 详情查看
  showDetailModal(item: any) {
    if (item.type === 1) {
      // SN管控
      this.snModalTable = !this.commonService.isEmpty(item.deliveryItemSns) ? JSON.parse(item.deliveryItemSns) : [];
      this.isSninfoVisible = true;
    } else {
      // 多库位
      this.locationOneTable = !this.commonService.isEmpty(item.deliveryLibraryText) ? JSON.parse(item.deliveryLibraryText).filter((ele: any) => ele.num) : [];
      this.locationTwoTable = !this.commonService.isEmpty(item.warehousingLibraryText) ? JSON.parse(item.warehousingLibraryText).filter((ele: any) => ele.num) : [];
      this.isDkwVisible = true;
    }
  }

  /**
   * SN 信息
   * ----------------------------------------------------------------
   */
  showSnInfosModal(item: any) {
    this.isSninfoVisible = true;
  }

  /**
   * 多库位 信息
   * ----------------------------------------------------------------
   */
  showLocationModal(item: any) {
    this.isDkwVisible = true;
  }

  /**
   * other
   * ----------------------------------------------------------------
   */

  // 入库数量 \ 单价合计
  calcSumTotal(key: string) {
    let sum = 0;
    const calcArrs = this.detailedTableData.filter(ele => ele.lineState === 0);
    sum = calcArrs.reduce((total: number, item: any) => {
      return (total || 0) + (item[key] || 0);
    }, 0);

    return isNaN(sum) ? 0 : sum;
  }

  // Filter Text
  filterText(arrs: Array<any>, keyVal: any, idKey: string) {
    let tempObjs: any = {};
    if (arrs.length) {
      tempObjs = arrs.find(item => item[idKey] == keyVal);
    }

    return tempObjs?.name || '-';
  }

  coprText(str: any) {
    this.commonService.copyStr(str);
  }

  downFile(item: any) {
    this.commonService.downLoadUrlFile(item.url);
  }

  pageBack() {
    history.back();
  }

  // 调入信息文字处理
  handleTransferText(item: any) {
    let arrs = [];
    let objs =  {
      goodProNum: 0, // 良品数
      rejectsNum: 0 // 不良品数
    };
    if (item.type === 1) {
      // SN管控
      arrs = !this.commonService.isEmpty(item.deliveryItemSns) ? JSON.parse(item.deliveryItemSns) : [];
    } else {
      arrs = !this.commonService.isEmpty(item.warehousingLibraryText) ? JSON.parse(item.warehousingLibraryText) : [];
    }

    objs.goodProNum = arrs.filter((ele: any) => ele.warehousingQuality === 1).length;
    objs.rejectsNum = arrs.filter((ele: any) => ele.warehousingQuality === 0).length;

    if (objs.goodProNum > 0 || objs.rejectsNum > 0) {
      return (objs.goodProNum > 0 ? `良品${objs.goodProNum}` : '') + (objs.rejectsNum > 0 ? ` 不良品${objs.rejectsNum}` : '');
    } else {
      return '-';
    }
  }

  // 明细调入调出颜色设置
  setTextColor(item: any) {
    let arrs = [];
    if (item.type === 1) {
      // SN管控
      arrs = !this.commonService.isEmpty(item.deliveryItemSns) ? JSON.parse(item.deliveryItemSns) : [];
    } else {
      arrs = !this.commonService.isEmpty(item.warehousingLibraryText) ? JSON.parse(item.warehousingLibraryText) : [];
    }
    let isDifferent = arrs.some((ele: any) => ele.deliveryQuality != item.deliveryQuality);

    return isDifferent ? '#F56C6C' : '';
  }
}
